package com.banyou.banyou.login.forget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banyou.banyou.R;
import com.banyou.banyou.base.BaseActivity;
import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.webutils.ProgressSubscriber;

import org.w3c.dom.Text;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class ForgetActivity extends BaseActivity<ForgetPresenter> implements ForgetContract.View {

    @BindView(R.id.title_bar)
    RelativeLayout mTitleBar;
    @BindView(R.id.next_btn)
    Button mNextBtn;
    @BindView(R.id.edit_phone)
    TextInputEditText mEditPhone;
    @BindView(R.id.edit_phone_content)
    TextInputLayout mEditPhoneContent;
    @BindView(R.id.send_code_btn)
    Button mSendCodeBtn;
    @BindView(R.id.edit_code)
    TextInputEditText mEditCode;
    @BindView(R.id.edit_code_content)
    TextInputLayout mEditCodeContent;
    @BindView(R.id.back_btn)
    ImageView mBackBtn;
    @BindView(R.id.info_content)
    RelativeLayout mInfoContent;
    @BindView(R.id.total_info_content)
    LinearLayout mTotalInfoContent;
    private ViewHolder mHolder;
    private View passwordModelView;

    @Override
    protected ForgetPresenter initPresenter() {
        return new ForgetPresenter();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_forget;
    }

    @Override
    protected View initLayoutView() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter.initPresenter(this, new ForgetModel());
        ButterKnife.bind(this);
        initNewPassword();
    }

    /**
     * 初始化重新输入密码模块
     */
    private void initNewPassword() {
        passwordModelView = LayoutInflater.from(this).inflate(R.layout.activity_forget_password, null);
        RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        passwordModelView.setLayoutParams(params);
        mHolder = new ViewHolder(passwordModelView);
    }

    @Override
    protected String pageName() {
        return "忘记密码页";
    }

    @OnClick({R.id.next_btn, R.id.send_code_btn, R.id.back_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.next_btn:
                //TODO 联网检查Code,然后下一步
                if (mEditPhone.getText().toString().trim().length() == 0||!isPhoneNum(mEditPhone.getText().toString())) {
                    mEditPhoneContent.setErrorEnabled(true);
                    mEditPhoneContent.setError("请填写正确的手机号");
                    return;
                }else if(mEditCode.getText().toString().trim().length()==0){
                    mEditCodeContent.setErrorEnabled(true);
                    mEditCodeContent.setError("请填写验证码");
                    return;
                }
                mPresenter.findPassword(mEditPhone.getText().toString(),mEditCode.getText().toString());
                break;
            case R.id.send_code_btn:
                if (mEditPhone.getText().toString().trim().length() != 0&&isPhoneNum(mEditPhone.getText().toString())) {
                    countTime();//倒计时60s
                    //联网获取验证码
                    mPresenter.getCode(mEditPhone.getText().toString());
                } else {
                    mEditPhoneContent.setErrorEnabled(true);
                    mEditPhoneContent.setError("请填写正确的手机号");
                }
                break;
            case R.id.back_btn:
                ForgetActivity.this.finish();
                break;
        }
    }

    /**
     * 切换下一个布局，密码输入页
     */
    private void nextLayout() {
        final int width=mInfoContent.getRight();
        ValueAnimator animator=ValueAnimator.ofFloat(0,-1);
        final ValueAnimator animator2=ValueAnimator.ofFloat(1,0);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mInfoContent.setLeft((int) (width*(float)animation.getAnimatedValue()));
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mInfoContent.removeAllViews();
                mInfoContent.addView(passwordModelView);
                animator2.start();
            }
        });
        animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mInfoContent.setLeft((int) (width*(float)animation.getAnimatedValue()));
            }
        });
        animator.start();
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mTimeCount--;
                    mSendCodeBtn.setClickable(false);
                    mSendCodeBtn.setText(mTimeCount + "秒后重发");
                    break;
                case 1:
                    mTimeCount = 60;
                    mSendCodeBtn.setClickable(true);
                    mSendCodeBtn.setText("重新发送");
                    break;
            }
        }
    };
    private int mTimeCount = 60;//倒计时

    /**
     * 点击发送验证码，倒计时60秒
     */
    private void countTime() {
        mTimeCount = 60;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (mTimeCount > 0) {
                    mHandler.sendEmptyMessage(0);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                mHandler.sendEmptyMessage(1);
            }
        });
        thread.start();
    }

    /**
     * 获取验证码成功
     */
    @Override
    public void getCodeSuccess() {
        Toast.makeText(this,"获取验证码成功",Toast.LENGTH_SHORT).show();

    }

    /**
     * 获取验证码失败
     */
    @Override
    public void getCodeFail(Throwable e) {
        if(e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            if(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg()!=null){
                Toast.makeText(this,((ProgressSubscriber.ReturnCodeErrorException) e).getMsg(),Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "获取验证码失败", Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(this, "获取验证码失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void findPasswordSuccess(String password) {
        nextLayout();
        mHolder.mNewPassWord.setText(password);
    }

    @Override
    public void findPasswordFailString(Throwable e) {
        if(e instanceof ProgressSubscriber.ReturnCodeErrorException){
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        }else {
            Toast.makeText(this, "找回密码失败", Toast.LENGTH_SHORT).show();
        }
    }


    static class ViewHolder {
        @BindView(R.id.new_password)
        TextView mNewPassWord;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 正则表达式
     * 判断电话号码是否有误
     *
     * @param phoneNum
     * @return
     */
    public boolean isPhoneNum(String phoneNum) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$");
        Matcher m = p.matcher(phoneNum);
        return m.matches();
    }
}
